package com.ecoolex.ying.space.admin.graphql;

import com.alibaba.fastjson.JSON;
import com.ecoolex.framework.common.pojo.Page;
import com.ecoolex.framework.common.pojo.Pagination;
import com.ecoolex.framework.common.pojo.Sorting;
import com.ecoolex.framework.common.util.Assert;
import com.ecoolex.framework.common.util.Check;
import com.ecoolex.framework.modularize.api.auth.admin.AdminMemberAuthority;
import com.ecoolex.framework.modularize.api.auth.annotation.AdminAuthoritativeRegister;
import com.ecoolex.framework.modularize.api.service.storage.*;
import com.ecoolex.framework.web.api.graphql2.annotation.*;
import com.ecoolex.ying.space.admin.core.AdminConstant;
import com.ecoolex.ying.space.entity.*;
import com.ecoolex.ying.space.pojo.*;
import com.ecoolex.ying.space.ws.GoodsService;
import com.google.common.collect.Lists;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;

import java.util.List;
import java.util.stream.Collectors;

import static com.ecoolex.framework.web.api.graphql2.annotation.GraphQL2Module.Type.Admin;
import static com.ecoolex.ying.space.admin.graphql.GoodsGaphql.AUTH;

@GraphQL2Module(type = Admin, description = "商品管理")
@AdminAuthoritativeRegister(parentKey = AdminConstant.AUTH_MODULE_KEY, key = AUTH, name = "商品管理")
public class GoodsGaphql {

    static final String AUTH = AdminConstant.AUTH_MODULE_KEY + "-GOODS";
    static final String AUTH_GET = AUTH + "-GET";
    static final String AUTH_QUERY = AUTH + "-QUERY";
    static final String AUTH_ADD = AUTH + "-ADD";
    static final String AUTH_EDIT = AUTH + "-EDIT";
    static final String AUTH_DEL = AUTH + "-DEL";

    static final UploadSource IMAGE_UPLOAD_SOURCE = new UploadSource("Goods", "Image");
    static final UploadLimit IMAGE_UPLOAD_LIMIT = new UploadLimit(FileSize.MB.byteLength(10), MimeType.IMAGE.commons());

    static final UploadSource DETAIL_UPLOAD_SOURCE = new UploadSource("Goods", "DetailImage");
    static final UploadLimit DETAIL_UPLOAD_LIMIT = new UploadLimit(FileSize.MB.byteLength(10), MimeType.IMAGE.commons());

    static final UploadSource SHOPWINDOW_IMAGES_UPLOAD_SOURCE = new UploadSource("Goods", "ShopwindowImages");
    static final UploadLimit SHOPWINDOW_IMAGES_UPLOAD_LIMIT = new UploadLimit(FileSize.MB.byteLength(10), MimeType.IMAGE.commons());

    static final UploadSource ATTACHMENT_UPLOAD_SOURCE = new UploadSource("Goods", "Attachment");
    static final UploadLimit ATTACHMENT_UPLOAD_LIMIT = new UploadLimit(FileSize.MB.byteLength(10), MimeType.IMAGE.commons());

    static final UploadSource MULTIPART_ATTACHMENT_UPLOAD_SOURCE = new UploadSource("Goods", "Attachment");
    static final UploadLimit MULTIPART_ATTACHMENT_UPLOAD_LIMIT = new UploadLimit(FileSize.MB.byteLength(300), MimeType.ALL.alls());

    static final UploadSource PRODUCT_IMAGE_UPLOAD_SOURCE = new UploadSource("GoodsProduct", "Image");
    static final UploadLimit PRODUCT_IMAGE_UPLOAD_LIMIT = new UploadLimit(FileSize.MB.byteLength(10), MimeType.IMAGE.commons());

    @Reference
    private GoodsService goodsService;
    @Autowired
    private StorageService storageService;

    @TypeField(type = GoodsWithBLOBs.class, field = "canEdit", description = "能否编辑")
    public boolean canEdit(@Source GoodsWithBLOBs source, AdminMemberAuthority user) {
        return user.auth(AUTH_EDIT);
    }

    @TypeField(type = GoodsWithBLOBs.class, field = "canDel", description = "能否删除")
    public boolean canDel(@Source GoodsWithBLOBs source, AdminMemberAuthority user) {
        return user.auth(AUTH_DEL);
    }

    @TypeField(type = GoodsWithBLOBs.class, field = "brand", description = "品牌")
    public GoodsBrand brand(@Source GoodsWithBLOBs source) {
        return Check.isNull(source.getBrandId()) ? null : goodsService.getBrandById(source.getBrandId());
    }

    @TypeField(type = GoodsWithBLOBs.class, field = "classify", description = "分类")
    public GoodsClassify classify(@Source GoodsWithBLOBs source) {
        return Check.isNull(source.getClassifyId()) ? null : goodsService.getClassifyById(source.getClassifyId());
    }

    @TypeField(type = GoodsWithBLOBs.class, field = "labelList", description = "标签列表")
    public List<GoodsLabel> labelList(@Source GoodsWithBLOBs source) {
        return goodsService.queryLabelByGoodsId(source.getGoodsId());
    }

    @TypeField(type = GoodsWithBLOBs.class, field = "image", description = "图片")
    public StorageInfo image(@Source GoodsWithBLOBs source) {
        return storageService.get(source.getImage());
    }

    @TypeField(type = GoodsWithBLOBs.class, field = "shopwindowImages", description = "橱窗图片列表")
    public List<StorageInfo> shopwindowImages(@Source GoodsWithBLOBs source) {
        if (Check.notNullOrTrimEmpty(source.getShopwindowImages())) {
            return JSON.parseArray(source.getShopwindowImages(), String.class).stream()
                    .map(storageService::get)
                    .filter(Check::notNull)
                    .collect(Collectors.toList());
        }
        return Lists.newArrayList();
    }

    @TypeField(type = GoodsWithBLOBs.class, field = "parameters", description = "参数")
    public GoodsParametersDTO parameters(@Source GoodsWithBLOBs source) {
        return Check.isNullOrTrimEmpty(source.getParameters()) ? null : JSON.parseObject(source.getParameters(), GoodsParametersDTO.class);
    }

    @TypeField(type = GoodsWithBLOBs.class, field = "attachmentList", description = "附件列表")
    public List<GoodsAttachment> attachmentList(@Source GoodsWithBLOBs source) {
        return goodsService.queryAttachmentByGoodsId(source.getGoodsId());
    }

    @TypeField(type = GoodsAttachment.class, field = "storageList", description = "存储文件列表")
    public List<StorageInfo> storageIds(@Source GoodsAttachment source) {
        return JSON.parseArray(source.getStorageIds(), String.class).stream()
                .map(storageService::get)
                .filter(Check::notNull)
                .collect(Collectors.toList());
    }

    @TypeField(type = GoodsWithBLOBs.class, field = "specGroupList", description = "规格分组列表")
    public List<GoodsSpecGroup> specGroupList(@Source GoodsWithBLOBs source) {
        return goodsService.querySpecGroupByGoodsId(source.getGoodsId());
    }

    @TypeField(type = GoodsSpecGroup.class, field = "specList", description = "规格列表")
    public List<GoodsSpec> specList(@Source GoodsSpecGroup source) {
        return goodsService.querySpecByGroupId(source.getSpecGroupId());
    }

    @TypeField(type = GoodsWithBLOBs.class, field = "productList", description = "产品列表")
    public List<GoodsProduct> productList(@Source GoodsWithBLOBs source) {
        return goodsService.queryProductByGoodsId(source.getGoodsId());
    }

    @TypeField(type = GoodsProduct.class, field = "image", description = "产品图片")
    public StorageInfo image(@Source GoodsProduct source) {
        return storageService.get(source.getImage());
    }

    @QueryField(field = "goods", description = "获取商品详情")
    @AdminAuthoritativeRegister(parentKey = AUTH, key = AUTH_GET, name = "获取商品详情")
    public GoodsWithBLOBs get(@NonNull Integer goodsId, AdminMemberAuthority user) {
        user.assertAuth(AUTH_GET);
        return goodsService.getGoodsById(goodsId);
    }

    @QueryField(field = "goodsList", description = "查询商品列表")
    @AdminAuthoritativeRegister(parentKey = AUTH, key = AUTH_QUERY, name = "查询商品列表")
    public Pagination<GoodsWithBLOBs> query(@NonNull QueryGoodsDTO query, @NonNull Sorting[] sorts, @NonNull Page page, AdminMemberAuthority user) {
        user.assertAuth(AUTH_QUERY);
        return goodsService.queryGoods(query, sorts, page);
    }

    @QueryField(field = "goodsSpecGroupList", description = "查询商品分组列表")
    public List<GoodsSpecGroup> goodsSpecGroupList(@NonNull Integer goodsId, AdminMemberAuthority user) {
        if (user.auth(AUTH_ADD) || user.auth(AUTH_EDIT)) {
            return goodsService.querySpecGroupByGoodsId(goodsId);
        } else {
            return user.notAuthority();
        }
    }

    @QueryField(field = "goodsProductList", description = "查询商品产品列表")
    public List<GoodsProduct> goodsProductList(@NonNull Integer goodsId, AdminMemberAuthority user) {
        if (user.auth(AUTH_ADD) || user.auth(AUTH_EDIT)) {
            return goodsService.queryProductByGoodsId(goodsId);
        } else {
            return user.notAuthority();
        }
    }

    @QueryField(field = "goodsAttachmentList", description = "查询商品附件列表")
    public List<GoodsAttachment> goodsAttachmentList(@NonNull Integer goodsId, AdminMemberAuthority user) {
        if (user.auth(AUTH_ADD) || user.auth(AUTH_EDIT)) {
            return goodsService.queryAttachmentByGoodsId(goodsId);
        } else {
            return user.notAuthority();
        }
    }

    @MutationField(field = "uploadGoodsDetailImage", description = "上传商品详情图片")
    public StorageInfo uploadGoodsDetailImage(@NonNull Upload request, AdminMemberAuthority user) {
        if (user.auth(AUTH_ADD) || user.auth(AUTH_EDIT)) {
            return storageService.upload(request, DETAIL_UPLOAD_SOURCE, DETAIL_UPLOAD_LIMIT);
        } else {
            return user.notAuthority();
        }
    }

    @MutationField(field = "uploadGoodsImage", description = "上传商品图片")
    public StorageInfo uploadGoodsImage(@NonNull Upload request, AdminMemberAuthority user) {
        if (user.auth(AUTH_ADD) || user.auth(AUTH_EDIT)) {
            return storageService.upload(request, IMAGE_UPLOAD_SOURCE, IMAGE_UPLOAD_LIMIT);
        } else {
            return user.notAuthority();
        }
    }

    @MutationField(field = "uploadGoodsShopwindowImages", description = "上传商品橱窗图片")
    public StorageInfo uploadGoodsShopwindowImages(@NonNull Upload request, AdminMemberAuthority user) {
        if (user.auth(AUTH_ADD) || user.auth(AUTH_EDIT)) {
            return storageService.upload(request, SHOPWINDOW_IMAGES_UPLOAD_SOURCE, SHOPWINDOW_IMAGES_UPLOAD_LIMIT);
        } else {
            return user.notAuthority();
        }
    }

    @MutationField(field = "uploadGoodsAttachment", description = "上传商品附件")
    public StorageInfo uploadGoodsAttachment(@NonNull Upload request, AdminMemberAuthority user) {
        if (user.auth(AUTH_ADD) || user.auth(AUTH_EDIT)) {
            return storageService.upload(request, ATTACHMENT_UPLOAD_SOURCE, ATTACHMENT_UPLOAD_LIMIT);
        } else {
            return user.notAuthority();
        }
    }

    @MutationField(field = "createGoodsAttachmentMultipartUpload", description = "创建商品附件分片上传")
    public MultipartUploadResult createGoodsAttachmentMultipartUpload(@NonNull MultipartUpload request, AdminMemberAuthority user) {
        if (user.auth(AUTH_ADD) || user.auth(AUTH_EDIT)) {
            return storageService.createMultipartUpload(request, MULTIPART_ATTACHMENT_UPLOAD_SOURCE, MULTIPART_ATTACHMENT_UPLOAD_LIMIT);
        } else {
            return user.notAuthority();
        }
    }

    @MutationField(field = "completeGoodsAttachmentMultipartUpload", description = "完成商品附件分片上传")
    public StorageInfo completeGoodsAttachmentMultipartUpload(@NonNull String uploadId) {
        return storageService.completeMultipartUpload(uploadId, MULTIPART_ATTACHMENT_UPLOAD_SOURCE);
    }

    @MutationField(field = "uploadGoodsProductImage", description = "上传商品产品图片")
    public StorageInfo uploadGoodsProductImage(@NonNull Upload request, AdminMemberAuthority user) {
        if (user.auth(AUTH_ADD) || user.auth(AUTH_EDIT)) {
            return storageService.upload(request, PRODUCT_IMAGE_UPLOAD_SOURCE, PRODUCT_IMAGE_UPLOAD_LIMIT);
        } else {
            return user.notAuthority();
        }
    }

    @MutationField(field = "addGoods", description = "添加商品")
    @AdminAuthoritativeRegister(parentKey = AUTH, key = AUTH_ADD, name = "添加商品")
    public GoodsWithBLOBs add(@NonNull EditGoodsDTO add, AdminMemberAuthority user) {
        user.assertAuth(AUTH_ADD);
        return goodsService.createGoods(add, user.userName());
    }

    @MutationField(field = "editGoods", description = "编辑商品")
    @AdminAuthoritativeRegister(parentKey = AUTH, key = AUTH_EDIT, name = "编辑商品")
    public boolean edit(@NonNull Integer goodsId, @NonNull EditGoodsDTO edit, AdminMemberAuthority user) {
        user.assertAuth(AUTH_EDIT);
        goodsService.updateGoods(goodsId, edit, user.userName());
        return true;
    }

    @MutationField(field = "editGoodsSpecGroup", description = "编辑商品规格")
    public boolean edit(@NonNull Integer goodsId, @NonNull List<EditSpecGroupDTO> specGroupList, AdminMemberAuthority user) {
        user.assertAuth(AUTH_EDIT);
        Goods goods = goodsService.getGoodsById(goodsId);
        Assert.isTrue(Check.notNull(goods), "商品不存在");
        goodsService.updateSpecGroup(goods, specGroupList, user.userName());
        return true;
    }

    @MutationField(field = "editGoodsProduct", description = "编辑商品产品")
    public boolean edit(@NonNull Integer goodsId, @NonNull EditGoodsProductDTO product, AdminMemberAuthority user) {
        user.assertAuth(AUTH_EDIT);
        Goods goods = goodsService.getGoodsById(goodsId);
        Assert.isTrue(Check.notNull(goods), "商品不存在");
        goodsService.updateProduct(product, user.userName());
        return true;
    }

    @MutationField(field = "editGoodsAttachment", description = "编辑商品附件")
    public boolean edit(@NonNull Integer goodsId,
                        @NonNull String[] imageStorageIds,
                        @NonNull String[] zipStorageIds,
                        @NonNull String[] videoStorageIds,
                        AdminMemberAuthority user) {
        user.assertAuth(AUTH_EDIT);
        Goods goods = goodsService.getGoodsById(goodsId);
        Assert.isTrue(Check.notNull(goods), "商品不存在");

        EditGoodsAttachmentDTO[] attachmentList = new EditGoodsAttachmentDTO[]{
                new EditGoodsAttachmentDTO().setType(1).setStorageIds(imageStorageIds),
                new EditGoodsAttachmentDTO().setType(2).setStorageIds(zipStorageIds),
                new EditGoodsAttachmentDTO().setType(3).setStorageIds(videoStorageIds),
        };

        goodsService.updateAttachment(goods, attachmentList, user.userName());
        return true;
    }

    @MutationField(field = "delGoods", description = "删除商品")
    @AdminAuthoritativeRegister(parentKey = AUTH, key = AUTH_DEL, name = "删除商品")
    public boolean del(@NonNull Integer goodsId, AdminMemberAuthority user) {
        user.assertAuth(AUTH_DEL);
        GoodsWithBLOBs goods = goodsService.getGoodsById(goodsId);
        Assert.isTrue(Check.notNull(goods), "商品不存在");
        goodsService.deleteGoods(goods, user.userName());
        return true;
    }
}
